/***************************************************
> Copyright (C) 2024 ==KINGYI== All rights reserved.
> File Name: pm8.8.one.c
> Author:
> Mail: 
> Created Time: Thu 08 Aug 2024 02:52:52 AM PDT
***************************************************/

// 线程1通过键盘输入两个数据，存入共享区域，线程2从中读取数据并计算两个数的和，打印结果

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>

sem_t semr,semw;
typedef struct EXAM
{
	int data1;
	int data2;
	int res;
}exam;

void *fun(void *arg)
{  
    
	exam *p = (exam *)arg;
	sem_wait(&semw);
	printf("please input data1 =\ndata2 =\n");
	scanf("%d%d",&p->data1,&p->data2);
	sem_post(&semr);
	
}

void *fun1( void *arg)
{
 exam *p =(exam *)arg;
 sem_wait(&semr);
 p->res =p->data1 + p->data2;
 printf("res =%d\n",p->res);
 sem_post(&semw);
}


int main(int argc,const char* argv[])
{
	pthread_t tid = 0,tid1 = 0;
	int ret = 0;
	int data1 = 0,data2 = 0;
	exam p;
	memset(&p,0,sizeof(exam));
	sem_init(&semw,0,1);
	sem_init(&semr,0,0);

	ret = pthread_create(&tid,NULL,fun,&p);
	if(ret != 0)
	{
		perror("pthread_create");
		exit(-1);
	}


	ret = pthread_create(&tid1,NULL,fun1,&p);
	if(ret != 0)
	{
		perror("pthread_create");
		exit(-1);
	}

	pthread_join(tid, NULL);
	pthread_join(tid1,NULL);

	sem_destroy(&semr);
	sem_destroy(&semw);
	return 0;
}
